package com.example.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/reports")
@Tag(name = "报表分析", description = "各种业务报表和数据分析")
public class ReportController {

    // ==================== 业务报表 ====================
    @GetMapping("/business/overview")
    @Operation(summary = "业务总览报表")
    public ResponseEntity<Map<String, Object>> getBusinessOverview(
            @RequestParam(required = false) String period,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        
        Map<String, Object> overview = new HashMap<>();
        
        // 核心指标
        overview.put("totalOrders", 1250L);
        overview.put("totalRevenue", 125000.0);
        overview.put("totalCustomers", 850L);
        overview.put("averageOrderValue", 100.0);
        
        // 增长率
        overview.put("orderGrowthRate", 15.5);
        overview.put("revenueGrowthRate", 22.3);
        overview.put("customerGrowthRate", 18.7);
        
        // 趋势数据
        overview.put("orderTrend", List.of(
            Map.of("date", "2024-11-01", "orders", 35, "revenue", 3500.0),
            Map.of("date", "2024-11-02", "orders", 42, "revenue", 4200.0),
            Map.of("date", "2024-11-03", "orders", 38, "revenue", 3800.0),
            Map.of("date", "2024-11-04", "orders", 45, "revenue", 4500.0),
            Map.of("date", "2024-11-05", "orders", 52, "revenue", 5200.0)
        ));
        
        return ResponseEntity.ok(overview);
    }

    @GetMapping("/business/orders")
    @Operation(summary = "订单分析报表")
    public ResponseEntity<Map<String, Object>> getOrderReport(
            @RequestParam(required = false) String period,
            @RequestParam(required = false) String groupBy) {
        
        Map<String, Object> report = new HashMap<>();
        
        // 订单状态分布
        report.put("statusDistribution", List.of(
            Map.of("status", "已完成", "count", 850, "percentage", 68.0),
            Map.of("status", "处理中", "count", 200, "percentage", 16.0),
            Map.of("status", "待确认", "count", 150, "percentage", 12.0),
            Map.of("status", "已取消", "count", 50, "percentage", 4.0)
        ));
        
        // 服务类型分布
        report.put("serviceDistribution", List.of(
            Map.of("service", "干洗", "count", 450, "revenue", 22500.0),
            Map.of("service", "水洗", "count", 600, "revenue", 18000.0),
            Map.of("service", "熨烫", "count", 200, "revenue", 4000.0)
        ));
        
        // 时间分布
        report.put("hourlyDistribution", List.of(
            Map.of("hour", 9, "count", 45),
            Map.of("hour", 10, "count", 65),
            Map.of("hour", 11, "count", 80),
            Map.of("hour", 14, "count", 75),
            Map.of("hour", 15, "count", 60),
            Map.of("hour", 16, "count", 55)
        ));
        
        return ResponseEntity.ok(report);
    }

    @GetMapping("/business/customers")
    @Operation(summary = "客户分析报表")
    public ResponseEntity<Map<String, Object>> getCustomerReport() {
        Map<String, Object> report = new HashMap<>();
        
        // 客户等级分布
        report.put("membershipDistribution", List.of(
            Map.of("level", "普通会员", "count", 600, "percentage", 70.6),
            Map.of("level", "银卡会员", "count", 150, "percentage", 17.6),
            Map.of("level", "金卡会员", "count", 80, "percentage", 9.4),
            Map.of("level", "白金会员", "count", 20, "percentage", 2.4)
        ));
        
        // 客户价值分析
        report.put("customerValue", List.of(
            Map.of("segment", "高价值客户", "count", 85, "avgOrderValue", 250.0, "totalRevenue", 21250.0),
            Map.of("segment", "中价值客户", "count", 255, "avgOrderValue", 120.0, "totalRevenue", 30600.0),
            Map.of("segment", "低价值客户", "count", 510, "avgOrderValue", 60.0, "totalRevenue", 30600.0)
        ));
        
        // 客户活跃度
        report.put("customerActivity", List.of(
            Map.of("period", "本月活跃", "count", 320),
            Map.of("period", "近3月活跃", "count", 580),
            Map.of("period", "半年内活跃", "count", 720),
            Map.of("period", "一年内活跃", "count", 850)
        ));
        
        return ResponseEntity.ok(report);
    }

    // ==================== 财务报表 ====================
    @GetMapping("/finance/summary")
    @Operation(summary = "财务汇总报表")
    public ResponseEntity<Map<String, Object>> getFinanceSummary(
            @RequestParam(required = false) String period) {
        
        Map<String, Object> summary = new HashMap<>();
        
        // 收入汇总
        summary.put("totalRevenue", 125000.0);
        summary.put("monthlyRevenue", 25000.0);
        summary.put("dailyRevenue", 850.0);
        
        // 支出汇总
        summary.put("totalExpenses", 45000.0);
        summary.put("monthlyExpenses", 9000.0);
        summary.put("dailyExpenses", 300.0);
        
        // 利润分析
        summary.put("grossProfit", 80000.0);
        summary.put("netProfit", 75000.0);
        summary.put("profitMargin", 60.0);
        
        // 收入构成
        summary.put("revenueBreakdown", List.of(
            Map.of("source", "订单收入", "amount", 120000.0, "percentage", 96.0),
            Map.of("source", "会员费", "amount", 3000.0, "percentage", 2.4),
            Map.of("source", "其他收入", "amount", 2000.0, "percentage", 1.6)
        ));
        
        return ResponseEntity.ok(summary);
    }

    @GetMapping("/finance/profit-loss")
    @Operation(summary = "损益报表")
    public ResponseEntity<Map<String, Object>> getProfitLossReport(
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        
        Map<String, Object> report = new HashMap<>();
        
        // 收入明细
        report.put("revenue", Map.of(
            "serviceRevenue", 120000.0,
            "membershipRevenue", 3000.0,
            "otherRevenue", 2000.0,
            "totalRevenue", 125000.0
        ));
        
        // 支出明细
        report.put("expenses", Map.of(
            "operatingExpenses", 25000.0,
            "salaryExpenses", 15000.0,
            "utilityExpenses", 3000.0,
            "marketingExpenses", 2000.0,
            "totalExpenses", 45000.0
        ));
        
        // 利润计算
        report.put("profit", Map.of(
            "grossProfit", 80000.0,
            "operatingProfit", 78000.0,
            "netProfit", 75000.0
        ));
        
        return ResponseEntity.ok(report);
    }

    // ==================== 运营报表 ====================
    @GetMapping("/operations/efficiency")
    @Operation(summary = "运营效率报表")
    public ResponseEntity<Map<String, Object>> getOperationEfficiency() {
        Map<String, Object> report = new HashMap<>();
        
        // 处理效率
        report.put("processingEfficiency", Map.of(
            "averageProcessingTime", 24.5, // 小时
            "onTimeDeliveryRate", 95.2,    // 百分比
            "customerSatisfactionRate", 4.6 // 评分
        ));
        
        // 设备利用率
        report.put("equipmentUtilization", List.of(
            Map.of("equipment", "洗衣机A", "utilizationRate", 85.5),
            Map.of("equipment", "洗衣机B", "utilizationRate", 78.2),
            Map.of("equipment", "烘干机A", "utilizationRate", 92.1),
            Map.of("equipment", "烘干机B", "utilizationRate", 88.7)
        ));
        
        // 员工效率
        report.put("staffEfficiency", List.of(
            Map.of("staff", "张三", "ordersProcessed", 45, "efficiency", 92.5),
            Map.of("staff", "李四", "ordersProcessed", 38, "efficiency", 88.2),
            Map.of("staff", "王五", "ordersProcessed", 42, "efficiency", 90.1)
        ));
        
        return ResponseEntity.ok(report);
    }

    // ==================== 库存报表 ====================
    @GetMapping("/inventory/analysis")
    @Operation(summary = "库存分析报表")
    public ResponseEntity<Map<String, Object>> getInventoryAnalysis() {
        Map<String, Object> report = new HashMap<>();
        
        // 库存概况
        report.put("overview", Map.of(
            "totalItems", 45,
            "totalValue", 15600.0,
            "lowStockItems", 5,
            "expiringItems", 2
        ));
        
        // 库存周转
        report.put("turnover", List.of(
            Map.of("item", "洗涤剂A", "turnoverRate", 12.5, "daysInStock", 29),
            Map.of("item", "柔顺剂B", "turnoverRate", 8.3, "daysInStock", 44),
            Map.of("item", "去污剂C", "turnoverRate", 15.2, "daysInStock", 24)
        ));
        
        // 采购建议
        report.put("purchaseRecommendations", List.of(
            Map.of("item", "洗涤剂A", "currentStock", 8, "recommendedOrder", 50),
            Map.of("item", "包装袋", "currentStock", 15, "recommendedOrder", 100)
        ));
        
        return ResponseEntity.ok(report);
    }

    // ==================== 自定义报表 ====================
    @PostMapping("/custom")
    @Operation(summary = "生成自定义报表")
    public ResponseEntity<Map<String, Object>> generateCustomReport(
            @RequestBody Map<String, Object> reportConfig) {
        
        Map<String, Object> report = new HashMap<>();
        report.put("reportId", "custom_" + System.currentTimeMillis());
        report.put("generatedAt", LocalDateTime.now());
        report.put("status", "COMPLETED");
        report.put("data", List.of(
            Map.of("metric", "自定义指标1", "value", 1250),
            Map.of("metric", "自定义指标2", "value", 85.5),
            Map.of("metric", "自定义指标3", "value", 125000.0)
        ));
        
        return ResponseEntity.ok(report);
    }

    @GetMapping("/templates")
    @Operation(summary = "获取报表模板")
    public ResponseEntity<List<Map<String, Object>>> getReportTemplates() {
        List<Map<String, Object>> templates = List.of(
            Map.of(
                "id", 1L,
                "name", "日营业报表",
                "description", "每日营业数据汇总",
                "category", "DAILY",
                "isActive", true
            ),
            Map.of(
                "id", 2L,
                "name", "月度财务报表",
                "description", "月度收支和利润分析",
                "category", "MONTHLY",
                "isActive", true
            ),
            Map.of(
                "id", 3L,
                "name", "客户分析报表",
                "description", "客户行为和价值分析",
                "category", "CUSTOMER",
                "isActive", true
            )
        );
        
        return ResponseEntity.ok(templates);
    }
}
